const PassportBiz = require('../../../../../comm/biz/passport_biz.js');
const pageHelper = require('../../../../../helper/page_helper.js');
const ProjectBiz = require('../../../biz/project_biz.js');
const RequestBiz = require('../../../../../comm/biz/request_biz.js');
const cacheHelper = require('../../../../../helper/cache_helper.js');
const constants = require('../../../../../comm/constants.js');
Page({
	/**
	 * 页面的初始数据
	 */
	data: {
		isLoad: false
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function (options) {
		ProjectBiz.initPage(this);
		if (!pageHelper.getOptions(this, options)) return;
    let user = PassportBiz.getToken();
		this.setData({
			user: user,
			status: options.status,
			maxCnt: options.maxCnt,
			_params: { activityId: this.data.id, userId: user? user.id : '' },
			isLoad: true,
			fields: 'id,activityId,userId,addTime,userPic,showName,currentUser,vipLevel,vipStyle,'
		});
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function () {
	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function () {
	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function () {
	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function () {
	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function () {
	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function () {
	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function () {

	},

	url: async function (e) {
		pageHelper.url(e, this);
	},

	bindCommListCmpt: function (e) {
		pageHelper.commListListener(this, e);
		this.insertMyNameIfNotExists();
	},

  // 修改接龙报名人
  bindChangeName: function(e) {
    let index = e.currentTarget.dataset.index;
    let val = e.detail.value;
		let dataList = this.data.dataList;
		dataList.list[index].showName = val;
    this.setData({
      dataList: dataList
    });
	},
	
  // 修改替补接龙报名人
  bindChangeReplaceName: function(e) {
    let index = e.currentTarget.dataset.index;
    let val = e.detail.value;
		let dataList = this.data.dataList;
		dataList.otherList[index].showName = val;
    this.setData({
      dataList: dataList
    });
	},
	
	bindAddTap: async function (e) {
    if (!this.data.user) {
      return;
    }
    let dataList = this.data.dataList;
    let allList = dataList.list.concat(dataList.otherList);
    let cnt = 0;
		for (let i = 0, len = allList.length; i < len; i++) {
			if (allList[i].currentUser) {
				cnt++;
			}
		}
		if (cnt >= 6) {
			pageHelper.showErrToast('求求了，别接了', 2000, null);
			return;
		}

		let obj = {
			currentUser: true,
			showName: this.data.user.name,
			userPic: this.data.user.pic,
			addTime: this.currentTime(),
			new: true,
			activityId: this.data.id,
			userId: this.data.user.id,
			activityId: this.data.id,
			vipLevel: this.data.user.vipLevel,
			vipStyle:  "vipBackground" + this.data.user.vipStyle,
		}
    if (allList.length < this.data.maxCnt) {
      dataList.list.push(obj);
    }
    else {
      dataList.otherList.push(obj);
    }
		this.setData({
			dataList: dataList
		});
	},
  
  // 查看用户信息
	bindUserInfoTap: async function (e) {
    let params = {
      id : e.currentTarget.dataset.user
    };
		let reqData = await RequestBiz.request('/api/ysjl/user/userInfo', params);
    let user = reqData.data.data;
		this.setData({
      showUserInfo: true,
			user
    });
    let radarName = cacheHelper.get(constants.CACHE_RADAR);
			if (!radarName) {
				let reqData = await RequestBiz.request("/api/ysjl/user/getDict", {code: 'radar'});
				radarName = reqData.data.data;
				cacheHelper.set(constants.CACHE_RADAR, radarName, constants.CACHE_RADAR_EXPIRE);
			}
			
			let _self = this;
			wx.createSelectorQuery().select('#canvas').boundingClientRect(function (rect) {
			}).exec(function (res) {
				_self.drawRadar({
					numCount: 6,
					numSlot: 5,
					x: res[0].width / 2,
					y: res[0].height / 2,
					radarName: radarName,
				}, user.userAbilityList);
			});
  },

  // 删除报名信息
	bindDeleteTap: async function (e) {
    let id = e.currentTarget.dataset.id;
    let index = e.currentTarget.dataset.index;
    if (!id) {
      this.delList(index);
      return;
    }

		let callback = async () => {
      wx.showLoading({ title: '删除报名信息' });
      let req = await RequestBiz.request('/api/ysjl/activity/deleteEnroll', {id: id, userName: null});
      if (req.data.ret != 0) {
        pageHelper.showErrToast(req.data.msg, 1000, async function () {
          wx.hideLoading();
        })
        return;
      }
      this.delList(index);
      wx.hideLoading();
		}
		pageHelper.showConfirm('确认删除？删除后报名数据将一并删除且不可恢复', callback);
  },
  
  delList: function(index) {
    let dataList = this.data.dataList;
    dataList.list.splice(index, 1);
    if (dataList.otherList && dataList.otherList.length > 0) {
      let otherData = dataList.otherList.shift();
      dataList.list.push(otherData);
    }
    this.setData({
      dataList: dataList
    });
  },
  
  // 删除替补列表
	bindDelReplaceTap: async function (e) {
    let id = e.currentTarget.dataset.id;
    let index = e.currentTarget.dataset.index;
    if (!id) {
      this.delReplaceList(index);
      return;
    }
		let callback = async () => {
      wx.showLoading({ title: '删除报名信息' });
        let req = await RequestBiz.request('/api/ysjl/activity/deleteEnroll', {id: id});
        wx.hideLoading();
        if (req.data.ret != 0) {
          pageHelper.showErrToast(req.data.msg, 1000, async function () {
            wx.hideLoading();
          })
          return;
        }
        this.delReplaceList(index);
        wx.hideLoading();
      }
    
		pageHelper.showConfirm('确认删除？删除后报名数据将一并删除且不可恢复', callback);
  },

  delReplaceList: function(index) {
    let dataList = this.data.dataList;
    dataList.otherList.splice(index, 1);
    this.setData({
      dataList: dataList
    });
  },

  // 接龙
	bindJoinTap: async function (e) {
		wx.showLoading({ title: '接龙中~' });
		let list = this.data.dataList.list.concat(this.data.dataList.otherList);
		if (list.length < 1) {
			wx.hideLoading();
			wx.navigateBack();
			return;
		}

    let myList = [];
    let nameMap = {};
		for (let i = 0, len = list.length; i < len; i++) {
			if (list[i].currentUser) {
        myList.push(list[i]);
        if (!list[i].showName) {
          pageHelper.showErrToast('写上接龙名字!', 2000, async function () {
            wx.hideLoading();
          });
          return;
        }
        if (!nameMap[list[i].showName]) {
          nameMap[list[i].showName] = true;
        }
        else {
          pageHelper.showErrToast('不要接重复名', 2000, async function () {
            wx.hideLoading();
          });
          return;
        }
			}
		}
		if (myList.length < 1) {
			wx.hideLoading();
			wx.navigateBack();
			return;
		}

		let req = RequestBiz.request('/api/ysjl/activity/join', myList);
		req.then(res => {
			wx.hideLoading();
			let retData = res.data;
			if (retData.ret == 0) {
				pageHelper.showSuccToast('是兄弟就来打球', 2000, async function () {
					wx.navigateBack();
				});
			}
			else {
				pageHelper.showErrToast(retData.msg, 2000, async function () {
					wx.hideLoading();
				});
			}
		});
  },
  
  bindLoginTap: function(e) {
    wx.reLaunch({
      url: pageHelper.fmtURLByPID('/pages/my/index/my_index'),
    });
  },

  // 插入名字
	insertMyNameIfNotExists: function() {
    let dataList = this.data.dataList;
    let allList = dataList.list.concat(dataList.otherList)
		for (let i = 0, len = allList.length; i < len; i++) {
			if (allList[i].currentUser) {
				return;
			}
		}

		this.bindAddTap(null);
	},

	currentTime: function() {
		let now = new Date(); // 获取当前时间
		let year = now.getFullYear(); // 获取当前年份
		let month = now.getMonth() + 1; // 获取当前月份，加“1”是因为月份是从0开始计算的，但实际月份是从1开始的
		let day = now.getDate(); // 获取当前日期
		let hours = now.getHours(); // 获取当前日期
		let minute = now.getMinutes(); // 获取当前日期
		let second = now.getSeconds(); // 获取当前日期
		return year + '-' + ('00' + month).substr(-2) + '-' + ('00' + day).substr(-2) + ' ' + hours + ':' + minute + ":" + second;
	},

	drawRadar:function (config, data) {
		let _self = this;
		wx.createSelectorQuery().select('#firstCanvas').context(function (res) {
			let context = null;
			context = res.context;
			config.mAngle = Math.PI * 2 / config.numCount;
			config.mRadius = 100;
			// 画边
			_self.drawEdge(config, context)
			// 绘制连接点
			_self.drawLinePoint(config, context)
			// 设置数据
      _self.drawRegion(config, context, data, '#C3CACA')
			// 设置文本数据
			_self.drawTextCans(config, context)
			// 设置节点
			_self.drawCircle(config, context, data, '#C3CACA')
			// 开始绘制
			context.draw()
		}).exec();
	},

	// 绘制6条边
  drawEdge: function(config, context){
    context.setStrokeStyle("#C3CACA")
    context.setLineWidth(2)  //设置线宽
		for (let i = 0; i < config.numSlot; i++) {
			//计算半径
			context.beginPath()
			let rdius = config.mRadius / config.numSlot * (i + 1)
			//画6条线段
			for (let j = 0; j < config.numCount; j++) {
				//坐标
				let x = config.x + rdius * Math.cos(config.mAngle * j);
				let y = config.y + rdius * Math.sin(config.mAngle * j);
        context.lineTo(x, y);
      }
      context.closePath()
      context.stroke()
    } 
	},
	
	// 绘制连接点
  drawLinePoint:function(config, context){
    context.beginPath();
		for (let k = 0; k < config.numCount; k++) {
			context.moveTo(config.x, config.y);
			let x = config.x + config.mRadius * Math.cos(config.mAngle * (k + 1));
			let y = config.y + config.mRadius * Math.sin(config.mAngle * (k + 1));
      context.lineTo(x, y);
    }
    context.stroke();
	},
	
 //绘制数据区域(数据和填充颜色)
	drawRegion: function (config, context, data, color){
		context.beginPath();
		for (let m = 0; m < config.numCount; m++){
			let x = config.x + config.mRadius * Math.cos(config.mAngle * m) * data[m].score / 100;
			let y = config.y + config.mRadius * Math.sin(config.mAngle * m) * data[m].score / 100;
			context.lineTo(x, y);
		}
		context.closePath();
		context.setFillStyle(color)
		context.fill();
	},
	
	//绘制文字
  drawTextCans: function (config, context){
		context.setFillStyle("#C3CACA")
		context.font = 'bold 17px cursive' //设置字体
		for (let n = 0; n < config.numCount; n++) {
			let x = config.x + config.mRadius * Math.cos(config.mAngle * n);
			let y = config.y + config.mRadius * Math.sin(config.mAngle * n);
			//通过不同的位置，调整文本的显示位置
			if (config.mAngle * n >= 0 && config.mAngle * n <= Math.PI / 2) {
				context.fillText(config.radarName[n], x + 5, y + 5);
			} else if (config.mAngle * n > Math.PI / 2 && config.mAngle * n <= Math.PI) {
				context.fillText(config.radarName[n], x - context.measureText(config.radarName[n]).width - 7, y + 5);
			} else if (config.mAngle * n > Math.PI && config.mAngle * n <= Math.PI * 3 / 2) {
				context.fillText(config.radarName[n], x - context.measureText(config.radarName[n]).width  -5, y);
			} else {
				context.fillText(config.radarName[n], x + 7, y + 2);
			}
		}
	},

	//画点
	drawCircle: function(config, context, data, color){
		let r = 3; //设置节点小圆点的半径
		for(let i = 0; i < config.numCount; i++){
			let x = config.x + config.mRadius * Math.cos(config.mAngle * i) * data[i].score / 100;
			let y = config.y + config.mRadius * Math.sin(config.mAngle * i) * data[i].score / 100;
			context.beginPath();
			context.arc(x, y, r, 0, Math.PI * 2);
			context.fillStyle = color;
			context.fill();
		}
	 },

})